package com.gulimall.member.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.gulimall.common.vo.WeiboAccessToken;
import com.gulimall.member.client.WeiboClient;
import com.gulimall.member.dao.MemberLevelDao;
import com.gulimall.member.entity.MemberLevelEntity;
import com.gulimall.member.exception.PhoneExistException;
import com.gulimall.member.exception.UserNameExistException;
import com.gulimall.member.vo.MemberLoginVo;
import com.gulimall.member.vo.MemberRegisterVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gulimall.common.utils.PageUtils;
import com.gulimall.common.utils.Query;

import com.gulimall.member.dao.MemberDao;
import com.gulimall.member.entity.MemberEntity;
import com.gulimall.member.service.MemberService;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Autowired
    private MemberLevelDao memberLevelDao;

    @Autowired
    private WeiboClient weiboClient;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void register(MemberRegisterVo memberRegisterVo) {
        MemberDao memberDao = this.baseMapper;
        MemberEntity memberEntity = new MemberEntity();

        //设置默认等级
        MemberLevelEntity levelEntity = memberLevelDao.getDefaultLevel();
        memberEntity.setLevelId(levelEntity.getId());
        //检查用户名和手机号是否唯一，为了能让controller感知异常，异常机制
        checkPhoneUnique(memberRegisterVo.getPhone());
        checkUserNameUnique(memberRegisterVo.getUserName());
        memberEntity.setUsername(memberRegisterVo.getUserName());
        memberEntity.setNickname(memberRegisterVo.getUserName());
        memberEntity.setMobile(memberRegisterVo.getPhone());

        //密码要进行加密存储
        //使用spring的工具类对密码进行MD5盐值加密
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encode = passwordEncoder.encode(memberRegisterVo.getPassword());
        memberEntity.setPassword(encode);
        memberDao.insert(memberEntity);

    }

    @Override
    public void checkPhoneUnique(String phone) throws PhoneExistException{
        MemberDao memberDao = this.baseMapper;
        Integer mobile = memberDao.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", phone));
        if (mobile > 0) {
            throw new PhoneExistException();
        }
    }

    @Override
    public void checkUserNameUnique(String userName) throws UserNameExistException{
        MemberDao memberDao = this.baseMapper;
        Integer count = memberDao.selectCount(new QueryWrapper<MemberEntity>().eq("username", userName));
        if (count > 0) {
            throw new UserNameExistException();
        }
    }

    @Override
    public MemberEntity login(MemberLoginVo vo) {
        String loginAccount = vo.getLoginAccount();
        String password = vo.getPassword();
        //1、去数据库中查询保存的密码
        MemberDao memberDao = this.baseMapper;
        MemberEntity entity = memberDao.selectOne(new QueryWrapper<MemberEntity>().eq("username", loginAccount).or().eq("mobile", loginAccount));
        if (entity == null) {
            return null;
        }else{
            //1、获取到数据库的password
            String passwordDB = entity.getPassword();
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            //2、密码匹配
            boolean matches = passwordEncoder.matches(password, passwordDB);
            if (matches) {
                return entity;
            }else {
                return null;
            }
        }
    }

    @Override
    public MemberEntity weiboLogin(WeiboAccessToken vo) {
        //登陆或者注册
        String uid = vo.getUid();
        MemberDao memberDao = this.baseMapper;
        MemberEntity memberEntity = memberDao.selectOne(new QueryWrapper<MemberEntity>().eq("social_id", uid));
        if (memberEntity != null) {
            //已注册
            memberEntity.setExpiresIn(vo.getExpiresIn());
            memberEntity.setAccessToken(vo.getAccessToken());
            memberDao.updateById(memberEntity);
            return memberEntity;
        }else{
            //未注册
            MemberEntity register = new MemberEntity();
            //查询社交用户的用户信息
            JSONObject weiboUserInfo = weiboClient.getWeiboUserInfo(vo.getAccessToken(), vo.getUid());
            register.setUsername(weiboUserInfo.getString("name"));
            register.setNickname(weiboUserInfo.getString("name"));
            register.setGender("m".equals(weiboUserInfo.getString("gender")) ? 1 : 0);
            register.setSocialId(vo.getUid());
            register.setAccessToken(vo.getAccessToken());
            register.setExpiresIn(vo.getExpiresIn());
            memberDao.insert(register);
            return register;
        }
    }
}





















